package com.shopping_back.serviceImpl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shopping_back.common.Result;
import com.shopping_back.mapper.*;
import com.shopping_back.pojo.entity.*;
import com.shopping_back.service.ISeckillItemService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 * 秒杀商品表 服务实现类
 * </p>
 *
 * @author Jack
 * @since 2025-07-12
 */
@Service
@RequiredArgsConstructor
public class SeckillItemServiceImpl extends ServiceImpl<SeckillItemMapper, SeckillItem> implements ISeckillItemService {
    private final PromotionActivityMapper promotionActivityMapper;
    private final SeckillItemMapper seckillItemMapper;
    private final OrderItemMapper orderItemMapper;
    private final OrderMainMapper orderMainMapper;

    private final RedissonClient redissonClient;
    private final ThreadPoolTaskExecutor taskExecutor;
    private final SkuMapper skuMapper;
    private final SpuMapper spuMapper;

    @Override
    public PromotionActivity getSeckillActivity(Long activityId) {
        PromotionActivity activity = promotionActivityMapper.selectById(activityId);
        if (activity == null) {
            return null;
        }
        return activity;
    }

    @Override
    public Page<SeckillItem> getSeckillItems(Long activityId, Integer page, Integer size) {
        Page<SeckillItem> itemPage = new Page<>(page, size);
        LambdaQueryWrapper<SeckillItem> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SeckillItem::getActivityId, activityId);
        seckillItemMapper.selectPage(itemPage, queryWrapper);

        // 填充商品图片和标题信息
        List<SeckillItem> records = itemPage.getRecords();
        if (!records.isEmpty()) {
            // 批量获取SKU IDs
            Set<Long> skuIds = records.stream()
                    .map(SeckillItem::getSkuId)
                    .collect(Collectors.toSet());

            // 批量查询SKU和SPU信息
            LambdaQueryWrapper<Sku> skuQueryWrapper = new LambdaQueryWrapper<>();
            skuQueryWrapper.in(Sku::getId, skuIds);
            List<Sku> skuList = skuMapper.selectList(skuQueryWrapper);

            // 创建SKU ID到SKU对象的映射
            Map<Long, Sku> skuMap = skuList.stream()
                    .collect(Collectors.toMap(Sku::getId, Function.identity()));

            // 批量查询SPU信息
            Set<Long> spuIds = skuList.stream()
                    .map(Sku::getSpuId)
                    .collect(Collectors.toSet());

            LambdaQueryWrapper<Spu> spuQueryWrapper = new LambdaQueryWrapper<>();
            spuQueryWrapper.in(Spu::getId, spuIds);
            List<Spu> spuList = spuMapper.selectList(spuQueryWrapper);

            // 创建SPU ID到SPU对象的映射
            Map<Long, Spu> spuMap = spuList.stream()
                    .collect(Collectors.toMap(Spu::getId, Function.identity()));

            // 填充图片和标题信息
            records.forEach(item -> {
                Sku sku = skuMap.get(item.getSkuId());
                if (sku != null) {
                    Spu spu = spuMap.get(sku.getSpuId());
                    if (spu != null) {
                        // 优先使用SKU图片，如果没有则使用SPU主图
                        String productImage = StringUtils.isNotBlank(sku.getSkuImage())
                                ? sku.getSkuImage()
                                : spu.getMainImage();
                        item.setProductImage(productImage);
                        item.setProductTitle(spu.getTitle());
                    }
                }
            });
        }
        return itemPage;
    }

//    @Override
//    public Page<OrderMain> getOrdersByActivity(Long activityId, Integer page, Integer size) {
//        Page<OrderMain> orderPage = new Page<>(page, size);
//        List<OrderMain> orders = orderItemMapper.selectOrdersByActivityId(activityId);
//        orderPage.setRecords(orders);
//        orderPage.setTotal(orders.size());
//        return orderPage;
//    }

    @Transactional(rollbackFor = Exception.class)
    public Result placeSeckillOrder(Long userId, Long activityId, Long skuId, Integer quantity) {
        String lockKey = "seckill:stock:" + skuId;
        RLock lock = redissonClient.getLock(lockKey);
        try {
            // 尝试获取分布式锁，等待3秒，锁10秒后自动释放
            if (!lock.tryLock(3, 10, TimeUnit.SECONDS)) {
                return Result.error("系统繁忙，请稍后重试");
            }

            // 检查活动状态
            PromotionActivity activity = promotionActivityMapper.selectById(activityId);
            if (activity == null || activity.getStatus() != 1 || LocalDateTime.now().isBefore(activity.getStartTime()) || LocalDateTime.now().isAfter(activity.getEndTime())) {
                return Result.error("活动不可用或已结束");
            }

            // 检查库存和限购
            SeckillItem seckillItem = seckillItemMapper.selectOne(new LambdaQueryWrapper<SeckillItem>()
                    .eq(SeckillItem::getActivityId, activityId)
                    .eq(SeckillItem::getSkuId, skuId));
            if (seckillItem == null) {
                return Result.error("秒杀商品不存在");
            }
            if (seckillItem.getSeckillStock() < quantity) {
                return Result.error("库存不足");
            }
            if (quantity <= 0 || quantity > seckillItem.getLimitPerUser()) {
                return Result.error("购买数量需在1至" + seckillItem.getLimitPerUser() + "件之间");
            }

            // 检查用户历史购买量
            Integer purchasedQuantity = orderItemMapper.selectSumQuantityByUserAndActivity(userId, activityId, skuId);
            if (purchasedQuantity == null) {
                purchasedQuantity = 0;
            }
            if (purchasedQuantity + quantity > seckillItem.getLimitPerUser()) {
                return Result.error("已超过单人限购数量，剩余可购" + (seckillItem.getLimitPerUser() - purchasedQuantity) + "件");
            }

            // 获取商家ID
            Sku sku = skuMapper.selectById(seckillItem.getSkuId());
            if (sku == null) {
                return Result.error("商品不存在");
            }
            Spu spu = spuMapper.selectById(sku.getSpuId());
            if (spu == null) {
                return Result.error("商品SPU不存在");
            }

            // 异步创建订单
            OrderMain orderMain = createOrder(userId, activityId, seckillItem, quantity, spu.getMerchantId(), spu.getTitle(), sku.getPrice());

            // 扣减库存
            seckillItem.setSeckillStock(seckillItem.getSeckillStock() - quantity);
            seckillItemMapper.update(
                    seckillItem,
                    new UpdateWrapper<SeckillItem>()
                            .eq("activity_id", seckillItem.getActivityId())
                            .eq("sku_id", seckillItem.getSkuId())
            );
            System.out.println(333);

            return Result.success( orderMain, "下单成功");
        } catch (InterruptedException e) {
            log.error("获取分布式锁失败", e);
            return Result.error("系统异常");
        } finally {
            if (lock.isHeldByCurrentThread()) {
                lock.unlock();
            }
        }
    }

    @Transactional(rollbackFor = Exception.class)
    protected OrderMain createOrder(Long userId, Long activityId, SeckillItem seckillItem, Integer quantity, Long merchantId, String skuName, BigDecimal originalPrice) {
        OrderMain order = new OrderMain();
        order.setOrderSn(UUID.randomUUID().toString().replace("-", ""));
        order.setUserId(userId);
        order.setTotalAmount(originalPrice.multiply(new BigDecimal(quantity))); // 原价 * 数量
        order.setPayAmount(seckillItem.getSeckillPrice().multiply(new BigDecimal(quantity))); // 秒杀价 * 数量
        order.setPromotionAmount(order.getTotalAmount().subtract(order.getPayAmount())); // 优惠金额 = 原价总额 - 秒杀价总额
        order.setStatus(0); // 待支付
        order.setMerchantId(merchantId);
        order.setCreateTime(LocalDateTime.now());
        order.setUpdateTime(LocalDateTime.now());
        orderMainMapper.insert(order);

        OrderItem orderItem = new OrderItem();
        orderItem.setOrderId(order.getId());
        orderItem.setSkuId(seckillItem.getSkuId());
        orderItem.setSkuName(skuName);
        orderItem.setSkuPrice(seckillItem.getSeckillPrice());
        orderItem.setQuantity(quantity);
        orderItem.setActivityId(activityId);
        orderItem.setSubTotal(seckillItem.getSeckillPrice().multiply(new BigDecimal(quantity)));
        orderItem.setCreateTime(LocalDateTime.now());
        orderItemMapper.insert(orderItem);

        return order;
    }
}
